package com.xiaoleilu.loServer.handler;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;

import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.StaticLog;
import com.xiaoleilu.hutool.util.CharsetUtil;
import com.xiaoleilu.hutool.util.DateUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.xiaoleilu.loServer.ServerSetting;
import com.xiaoleilu.loServer.listener.FileProgressiveFutureListener;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
import org.slf4j.LoggerFactory;

public class Response {
    private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(Response.class);

	public final static String CONTENT_TYPE_TEXT = "text/plain";
	public final static String CONTENT_TYPE_HTML = "text/html";
	public final static String CONTENT_TYPE_XML = "text/xml";
	public final static String CONTENT_TYPE_JAVASCRIPT = "application/javascript";
	public final static String CONTENT_TYPE_JSON = "application/json";
	public final static String CONTENT_TYPE_JSON_IE = "text/json";

	private ChannelHandlerContext ctx;
	private Request request;

	private HttpVersion httpVersion = HttpVersion.HTTP_1_1;
	private HttpResponseStatus status = HttpResponseStatus.OK;
	private String contentType = CONTENT_TYPE_HTML;
	private String charset = ServerSetting.getCharset();
	private HttpHeaders headers = new DefaultHttpHeaders();
	private Set<Cookie> cookies = new HashSet<Cookie>();
	private Object content = Unpooled.EMPTY_BUFFER;
	private boolean isSent;

	public Response(ChannelHandlerContext ctx, Request request) {
		this.ctx = ctx;
		this.request = request;
	}

	public Response setHttpVersion(HttpVersion httpVersion) {
		this.httpVersion = httpVersion;
		return this;
	}

	public Response setStatus(HttpResponseStatus status) {
		this.status = status;
		return this;
	}

	public Response setStatus(int status) {
		return setStatus(HttpResponseStatus.valueOf(status));
	}

	public Response setContentType(String contentType) {
		this.contentType = contentType;
		return this;
	}

	public Response setCharset(String charset) {
		this.charset = charset;
		return this;
	}

	public Response addHeader(String name, Object value) {
		headers.add(name, value);
		return this;
	}

	public Response setHeader(String name, Object value) {
		headers.set(name, value);
		return this;
	}

	public Response setContentLength(long contentLength) {
		setHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), contentLength);
		return this;
	}

	public Response setKeepAlive() {
		setHeader(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
		return this;
	}

	public Response addCookie(Cookie cookie) {
		cookies.add(cookie);
		return this;
	}

	public Response addCookie(String name, String value) {
		return addCookie(new DefaultCookie(name, value));
	}

	public Response addCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
		Cookie cookie = new DefaultCookie(name, value);
		if (domain != null) {
			cookie.setDomain(domain);
		}
		cookie.setMaxAge(maxAgeInSeconds);
		cookie.setPath(path);
		return addCookie(cookie);
	}

	public Response addCookie(String name, String value, int maxAgeInSeconds) {
		return addCookie(name, value, maxAgeInSeconds, "/", null);
	}

	public Response setContent(String contentText) {
		this.content = Unpooled.copiedBuffer(contentText, Charset.forName(charset));
		return this;
	}
	
	public Response setTextContent(String contentText) {
		setContentType(CONTENT_TYPE_TEXT);
		return setContent(contentText);
	}
	
	public Response setJsonContent(String contentText) {
		setContentType(request.isIE() ? CONTENT_TYPE_JSON : CONTENT_TYPE_JSON);
		return setContent(contentText);
	}
	
	public Response setXmlContent(String contentText) {
		setContentType(CONTENT_TYPE_XML);
		return setContent(contentText);
	}

	public Response setContent(byte[] contentBytes) {
		return setContent(Unpooled.copiedBuffer(contentBytes));
	}

	public Response setContent(ByteBuf byteBuf) {
		this.content = byteBuf;
		return this;
	}
	
	public Response setContent(File file) {
		this.content = file;
		return this;
	}

	public void setDateAndCache(long lastModify, int httpCacheSeconds) {
		SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.HTTP_DATETIME_PATTERN, Locale.US);
		formatter.setTimeZone(TimeZone.getTimeZone("GMT"));

		// Date header
		Calendar time = new GregorianCalendar();
		setHeader(HttpHeaderNames.DATE.toString(), formatter.format(time.getTime()));

		// Add cache headers
		time.add(Calendar.SECOND, httpCacheSeconds);

		setHeader(HttpHeaderNames.EXPIRES.toString(), formatter.format(time.getTime()));
		setHeader(HttpHeaderNames.CACHE_CONTROL.toString(), "private, max-age=" + httpCacheSeconds);
		setHeader(HttpHeaderNames.LAST_MODIFIED.toString(), formatter.format(DateUtil.date(lastModify)));
	}

	private DefaultHttpResponse toDefaultHttpResponse() {
		final DefaultHttpResponse defaultHttpResponse = new DefaultHttpResponse(httpVersion, status);

		// headers
		final HttpHeaders httpHeaders = defaultHttpResponse.headers().add(headers);

		// Cookies
		for (Cookie cookie : cookies) {
			httpHeaders.add(HttpHeaderNames.SET_COOKIE.toString(), ServerCookieEncoder.LAX.encode(cookie));
		}

		return defaultHttpResponse;
	}

	private FullHttpResponse toFullHttpResponse() {
		final ByteBuf byteBuf = (ByteBuf)content;
		final FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpVersion, status, byteBuf);

		// headers
		final HttpHeaders httpHeaders = fullHttpResponse.headers().add(headers);
		if ("application/octet-stream".equals(contentType)) {
            httpHeaders.set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        } else {
            httpHeaders.set(HttpHeaderNames.CONTENT_TYPE.toString(), StrUtil.format("{};charset={}", contentType, charset));
            httpHeaders.set(HttpHeaderNames.CONTENT_ENCODING.toString(), charset);
        }

		httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH.toString(), byteBuf.readableBytes());

		// Cookies
		for (Cookie cookie : cookies) {
			httpHeaders.add(HttpHeaderNames.SET_COOKIE.toString(), ServerCookieEncoder.LAX.encode(cookie));
		}

		return fullHttpResponse;
	}

	public ChannelFuture send() {
		ChannelFuture channelFuture;
		if(content instanceof File){
			File file = (File)content;
			try {
				channelFuture = sendFile(file);
			} catch (IOException e) {
                Logger.error(StrUtil.format("Send {} error!", file), e.toString());
				channelFuture = sendError(HttpResponseStatus.FORBIDDEN, "");
			}
		}else{
			channelFuture = sendFull();
		}
		
		this.isSent = true;
		return channelFuture;
	}

	protected boolean isSent(){
		return this.isSent;
	}
	
	private ChannelFuture sendFull() {
		if (request != null && request.isKeepAlive()) {
			setKeepAlive();
			return ctx.writeAndFlush(this.toFullHttpResponse());
		} else {
			return sendAndCloseFull();
		}
	}
	
	private ChannelFuture sendAndCloseFull() {
		return ctx.writeAndFlush(this.toFullHttpResponse()).addListener(ChannelFutureListener.CLOSE);
	}
	
	private ChannelFuture sendFile(File file) throws IOException {
		final RandomAccessFile raf = new RandomAccessFile(file, "r");
		
		long fileLength = raf.length();
		this.setContentLength(fileLength);
		
		String contentType = HttpUtil.getMimeType(file.getName());
		if(StrUtil.isBlank(contentType)){
			contentType = "application/octet-stream";
		}
		this.setContentType(contentType);
		
		ctx.write(this.toDefaultHttpResponse());
		ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise())
			.addListener(FileProgressiveFutureListener.build(raf));
		
		return sendEmptyLast();
	}
	
	private ChannelFuture sendEmptyLast(){
		final ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
		if (false == request.isKeepAlive()) {
			lastContentFuture.addListener(ChannelFutureListener.CLOSE);
		}
		
		return lastContentFuture;
	}

	public ChannelFuture sendRedirect(String uri) {
		return this.setStatus(HttpResponseStatus.FOUND).setHeader(HttpHeaderNames.LOCATION.toString(), uri).send();
	}

	public ChannelFuture sendNotModified() {
		return this.setStatus(HttpResponseStatus.NOT_MODIFIED).setHeader(HttpHeaderNames.DATE.toString(), DateUtil.formatHttpDate(DateUtil.date())).send();
	}

	public ChannelFuture sendError(HttpResponseStatus status, String msg) {
		if (ctx.channel().isActive()) {
			return this.setStatus(status).setContent(msg).send();
		}
		return null;
	}

	public ChannelFuture sendNotFound(String msg) {
		return sendError(HttpResponseStatus.NOT_FOUND, msg);
	}

	public ChannelFuture sendServerError(String msg) {
		return sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, msg);
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder();
		sb.append("headers:\r\n ");
		for ( Entry<String, String> entry : headers.entries()) {
			sb.append("    ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
		}
		sb.append("content: ").append(StrUtil.str(content, CharsetUtil.UTF_8));

		return sb.toString();
	}

	protected static Response build(ChannelHandlerContext ctx, Request request) {
		return new Response(ctx, request);
	}

	protected static Response build(ChannelHandlerContext ctx) {
		return new Response(ctx, null);
	}
}
